import React, { useState, useEffect } from 'react';
import {Card, Table, Pagination, Divider, ResponsiveGrid, Button, Box, Form, Input, Select, Icon, Radio, Upload, Loading,Dialog,Message, } from '@alifd/next';
import styles from './index.module.scss';
import {optionCourseList} from '@/api/CourseAPI'
import {optionChapterList} from '@/api/CourseChapterAPI'
import {listPage, publish, downShelf, deleteQuestion, detail, update} from '@/api/CourseQuestionAPI'
import AddCourseQuestion from '../AddCourseQuestion/AddCourseQuestion'
import UpdateCourseQuestion from '../UpdateCourseQuestion/UpdateCourseQuestion'
import DetailCourseQuestion from '../DetailCourseQuestion/DetailCourseQuestion'

const { Cell } = ResponsiveGrid;
const { Option } = Select;
const FormItem = Form.Item;

// 题目类型，1:选择题，2:填空题，3:简答题，4:阅读理解，5:作文题，6:应用题
const questionTypesData = [
  {value: "1", label:"选择题"},
  {value: "2", label:"填空题"},
  {value: "3", label:"简答题"},
  {value: "4", label:"阅读理解"},
  {value: "5", label:"作文题"},
  {value: "6", label:"计算题"},

];
// 课程-题目状态,0:正常，1:停用，2:已发布,3:已下架, 默认为 0
const questionStatesData = [
  {value:'0', label:"未发布"},
  {value:'1', label:"停用"},
  {value:'2', label:"已发布"},
  {value:'3', label:"已下架"}
];
const DEFAULT_DATA = {
  questionTypes: questionTypesData,
  questionStates: questionStatesData,
  questionList: [],
  // 查询参数
  QueryParam: {
    page:{
      current: 1,
      size: 10
    },
    query: "",
    state: null,
    type: null,
    courseId: null,
    chapterId: null,
  },
  total: 0,
};

/**
 * 课程-题目列表组件
 * 日期：2020-06-22
 */
class CourseQuestionList extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
        dataSource: DEFAULT_DATA,
        loading: true,
        courseOptionList: [],
        courseBaseOption: [],
    };

  }
  // 初始化方法
  componentDidMount(){
    this.loadCourseOptionList();
    this.onOperation();
  };
  // 加载课程下拉列表动作
  loadCourseOptionList = () => {
    optionCourseList().then((data)=>{
      if(data){
        var oList = []
        data.map((item, index)=>{
          oList[index] = {
            value: item.id,
            label: item.name,
          }
        });
        this.setState({ 
          courseOptionList: oList,
          courseBaseOption: data,
        }) 
      }
    });
  };
  // 加载列表动作
  onOperation = () => {
      // 1.1 调用 UserAPI listPage 接口
      listPage(DEFAULT_DATA.QueryParam).then((data)=>{
        if(data){
          const list = data.records;
          // 处理状态、类型
          if(list){
            for (const i in list) {
              const v = list[i]
              // 处理状态
              for(const j in questionStatesData){
                const s = questionStatesData[j]
                let st = '' + v.state;
                if(st == s.value){
                  v.stateV = s.label
                }
              }
            }
          }
          DEFAULT_DATA.total = data.total;
          DEFAULT_DATA.questionList = list;
          this.setState({ 
            DEFAULT_DATA,
            loading: false,
          }) 
        }
      });
  };

  // 动态变更课程-题目 模糊条件
  changeQuery = (e) => {
    DEFAULT_DATA.QueryParam.query = e
  };
  // 动态变更课程-题目 状态
  changeQuestionState = (e) => {
    DEFAULT_DATA.QueryParam.state = e
  };
  // 动态变更课程-题目类型
  changeQuestionTypes = (e) => {
    DEFAULT_DATA.QueryParam.type = e
  };
  // 变更课程选项
  changeCourseId = (e) => {
    DEFAULT_DATA.QueryParam.courseId = e
  };
  
  // 重置
  onReset = (v) => {
    DEFAULT_DATA.QueryParam.type = null
    DEFAULT_DATA.QueryParam.state = null
    DEFAULT_DATA.QueryParam.query = null
    DEFAULT_DATA.QueryParam.courseId = null
    this.state = {
      DEFAULT_DATA,
      queryValue:'',
    };
  };
  // 下架事件
  downShelfButton = (v) => {
    Dialog.confirm({
      title: '是否下架',
      onOk: () => {
        downShelf(v).then((flag)=>{
          if(flag){
            Message.success('下架成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 发布事件
  publishButton = (v) => {
    Dialog.confirm({
      title: '是否发布',
      onOk: () => {
        publish(v).then((flag)=>{
          if(flag){
            Message.success('发布成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 删除
  delButton = (v) => {
    Dialog.confirm({
      title: '是否确定要删除',
      onOk: () => {
        deleteQuestion(v).then((flag)=>{
          if(flag){
            Message.success('删除成功')
            // 刷新列表数据
            this.onOperation();
          }
        })
      },
    })
  };
  // 分页查询：
  onPaginationChange = (e) => {
    DEFAULT_DATA.QueryParam.page.current = e 
    this.state = {
      DEFAULT_DATA
    };
    this.onOperation();
  };
  // 点击查询
  onFindCourse = () =>{
    DEFAULT_DATA.QueryParam.page.current = 1
    this.state = {
      DEFAULT_DATA
    };
    this.onOperation();
  };

  handlerOperatorButton = (value, index, model) =>{
      // 课程-题目状态,0:正常，1:停用，2:已发布,3:已下架, 默认为 0
      if(model.state == 0 || model.state == 3){
        return (
          <div className={styles.opt}>
            <Button type="primary" text  onClick={()=>this.openUpdateCourseChapter(model.id)}>编辑</Button>
            <Button type="primary" text style={{color: 'green'}} onClick={()=> this.publishButton(model.id) }>发布</Button>
            <Button type="primary" text style={{color: 'red'}} onClick={()=> this.delButton(model.id)}>删除</Button>
          </div>
        )
      }else if(model.state == 2){
        return (
          <div className={styles.opt}>
            <Button type="primary" text style={{color: 'black'}} onClick={()=> this.downShelfButton(model.id)}>下架</Button>
          </div>
        )
      }
  };
  // 打开新增页面
  openAddCourseQuestion = () =>{
    this.AddCourseQuestion.onOpen(this.state.courseOptionList, questionTypesData, questionStatesData) 
  };
  // 新增组件引用
  onRefAddCourseQuestion = (ref) => {
    this.AddCourseQuestion = ref
  }
  // 打开修改页面
  openUpdateCourseChapter = (key) =>{
      this.UpdateCourseQuestion.onOpen(key, this.state.courseOptionList, questionTypesData, questionStatesData) 
  };
  // 修改组件引用
  onRefUpdateCourseChapter = (ref) => {
    this.UpdateCourseQuestion = ref
  }
  // 新增或修改 回调刷新列表
  onFreshList = () => {
    this.onOperation();
  }
  // 打开详情页面
  openDetailCourseQuestion = (key) =>{
    // console.log('****打开详情页面****', key)
    this.DetailCourseQuestion.onOpen(key, this.state.courseOptionList, questionTypesData, questionStatesData) 
  };
  // 详情组件引用
  onRefDetailCourseQuestion = (ref) => {
    this.DetailCourseQuestion = ref
  }
  // 根据课程ID, 查看课程名称、代码，提供给新增、修改组件使用
  getCourseInfo = (key) => {
    // console.log('****父组件****', key)
    return this.state.courseBaseOption.filter((item)=>{
      if(key === item.id){
        // console.log('****找到了一个组件****',item)
        return item;
      }
    })[0];
  };

  render(){
    return (
      <>
        <Card free>
          <Card.Content>
            <Box padding={10}>
              <Form responsive fullWidth labelAlign="top">
                <FormItem  colSpan={2} label="模糊条件">
                  <Input name='queryParam' onChange={this.changeQuery} placeholder="支持章节、题干、答案" hasClear/>
                </FormItem>
                <FormItem colSpan={2} label="题目状态">
                  <Select name='courseState' placeholder="选择状态" dataSource= {this.state.dataSource.questionStates || []} onChange={this.changeQuestionState} hasClear/>
                </FormItem>
                <FormItem colSpan={2} label="题目类型">
                  <Select name='courseType' placeholder="选择类型" dataSource= {this.state.dataSource.questionTypes || []} onChange={this.changeQuestionTypes} hasClear/>
                </FormItem>
                <FormItem colSpan={2} label="所属课程">
                  <Select name='courseId' placeholder="选择课程" dataSource= {this.state.courseOptionList || []} onChange={this.changeCourseId} hasClear/>
                </FormItem>
                <Cell colSpan={3} className={styles.btns}>
                  <Box spacing={8} direction="row" align="flex-end" justify="center" style={{height: '100%',}}>
                    <Button type="primary" onClick={this.onFindCourse}>查询</Button>
                    <Form.Reset onClick={this.onReset} names={['courseState','courseType','queryParam','courseId']}>重置</Form.Reset>
                  </Box>
                </Cell>
              </Form>
            </Box>
            <Divider dashed />
            <div className={styles.Main}>
              <Loading visible={this.state.loading}>
                <div className={styles.add}>
                  <AddCourseQuestion onRef={this.onRefAddCourseQuestion} onFreshList = {this.onFreshList} getCourseInfo={this.getCourseInfo} />
                  <UpdateCourseQuestion onRef={this.onRefUpdateCourseChapter} onFreshList = {this.onFreshList} getCourseInfo={this.getCourseInfo}/>
                  <DetailCourseQuestion onRef={this.onRefDetailCourseQuestion} getCourseInfo={this.getCourseInfo} />
                  <Button type="primary" onClick={this.openAddCourseQuestion}>新增题目</Button>
                </div>
                <Table
                  hasBorder={false}
                  className={styles.Table}
                  dataSource={this.state.dataSource.questionList}
                  rowSelection={{
                    columnProps: () => ({
                      lock: 'left',
                    }),
                  }}
                >
                  <Table.Column title="标识" dataIndex="id"  width={80} 
                    cell = {(key) =>(<a onClick={()=>this.openDetailCourseQuestion(key)}>
                        <span style={{ color: "blue", cursor: "pointer"}}>{key}</span>
                      </a>)}
                  />
                  <Table.Column title="课程" dataIndex="courseSmallName" key='courseSmallName' width={140}/>
                  <Table.Column title="章节" dataIndex="chapterSmallName" key='chapterSmallName' width={100}/>
                  <Table.Column title="题目类型" dataIndex="typeName" key='typeName' width={100}/>
                  <Table.Column title="题干" dataIndex="main" key='main' width={600}/>
                  <Table.Column title="排序" dataIndex="sort" key='sort' width={80}/>
                  <Table.Column title="状态" dataIndex="stateV" key='state' width={100}/>
                  <Table.Column title="发布时间" dataIndex="publishTime" key='publishTime' width={150}/>
                  <Table.Column title="操作" cell={this.handlerOperatorButton} />
                </Table>
                <Box margin={[15, 0, 0, 0]} direction="row" align="center" justify="space-between">
                  <div className={styles.total}>
                    每页<span>{this.state.dataSource.QueryParam.page.size}</span>条，共<span>{this.state.dataSource.total}</span>条
                  </div>
                  <Pagination pageSize={this.state.dataSource.QueryParam.page.size} total={this.state.dataSource.total} onChange={this.onPaginationChange} />
                </Box>
              </Loading>
            </div>
          </Card.Content>
        </Card>
      </>
    );
  };
}

export default CourseQuestionList;